package com.mall.controller;

import java.util.HashMap;
import java.util.Map;

import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.entity.Users;
import com.mall.mapper.UsersMapper;
import com.mall.ultis.JsonResult;
import com.mall.ultis.ParamCheck;
import com.mall.ultis.Result;
import com.mall.ultis.JwtHelper;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/auth")
public class AuthorizeController {

    @Autowired
    private JwtHelper jwtHelper;

    @Resource
    UsersMapper usersMapper;

    @PostMapping("/login")
    public Result login(@ParamCheck Users users) {

        Map< String, Object > claims = new HashMap< String, Object >();

//        if (users.getUsername() == null) {
//            return Result.error( "缺少参数username" );
//        }
//
//        if (users.getPassword().equals( null ) ) {
//            return Result.error( "缺少参数password" );
//        }

        // md5
        Digester digester = new Digester( DigestAlgorithm.MD5);

        String password = digester.digestHex(users.getPassword());

        QueryWrapper queryWrapper = new QueryWrapper<Users>(  );
        queryWrapper.eq( "username", users.getUsername());
        queryWrapper.eq( "password", password);

        Users user = usersMapper.selectOne( queryWrapper );

        if (user != null) {
            claims.put("username", users.getUsername());
            claims.put("id", user.getId());
            claims.put("phone", user.getPhone());
            claims.put("name", user.getName());
            return Result.success( jwtHelper.generateToken( claims ) );
        }

        return Result.error( "账号或者密码错误。" );

    }

}
